package com.terabits.smartriver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.terabits.smartriver.constants.result.BaseResp;
import com.terabits.smartriver.constants.result.ResultStatus;
import com.terabits.smartriver.mapper.BoxDataMapper;
import com.terabits.smartriver.mapper.DeviceMapper;
import com.terabits.smartriver.mapper.ProjectMapper;
import com.terabits.smartriver.meta.dto.MongoData;
import com.terabits.smartriver.meta.po.BoxData;
import com.terabits.smartriver.meta.po.Concentration;
import com.terabits.smartriver.meta.po.Device;
import com.terabits.smartriver.meta.po.Project;
import com.terabits.smartriver.service.DataViewService;
import com.terabits.smartriver.util.MongoManager;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.terabits.smartriver.util.DateUtils.*;

@CrossOrigin
@RestController
public class DataStatisticsController extends BaseController {
    @Autowired
    private DataViewService dataViewService;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Resource
    private MongoManager mongoManager;
    @Autowired
    private BoxDataMapper boxDataMapper;

    @ApiOperation(value = "查看 企业", tags = {"企业管理-监控地图"})
    @RequestMapping(value = "/enterprise-mgt/map/enterprise/get", method = RequestMethod.GET)
    public BaseResp getMapEnterprise() {
//color: 0灰色 1绿色 2黄色 3红色
//        String test = "[{\"projects\":[{\"alarms\":1,\"project\":\"项目一\",\"status\":\"异常\"},{\"alarms\":0,\"project\":\"项目二\",\"status\":\"正常\"}],\"latitude\":30.880061,\"name\":\"某A企业\",\"id\":1,\"longitude\":120.086399,\"color\":3},{\"projects\":[{\"alarms\":1,\"project\":\"项目一\",\"status\":\"正常\"}],\"latitude\":30.873615,\"name\":\"某D企业\",\"id\":1,\"longitude\":120.069008,\"color\":1},{\"projects\":[{\"alarms\":1,\"project\":\"项目一\",\"status\":\"警告\"},{\"alarms\":0,\"project\":\"项目二\",\"status\":\"正常\"}],\"latitude\":30.869554,\"name\":\"某C企业\",\"id\":1,\"longitude\":120.026436,\"color\":2},{\"projects\":[{\"alarms\":1,\"project\":\"项目一\",\"status\":\"关闭\"},{\"alarms\":0,\"project\":\"项目二\",\"status\":\"关闭\"}],\"latitude\":30.909393,\"name\":\"某E企业\",\"id\":1,\"longitude\":120.084897,\"color\":0},{\"projects\":[{\"alarms\":1,\"project\":\"项目一\",\"status\":\"异常\"},{\"alarms\":0,\"project\":\"项目二\",\"status\":\"正常\"},{\"alarms\":5,\"project\":\"项目三\",\"status\":\"异常\"}],\"latitude\":30.878127,\"name\":\"某F企业\",\"id\":1,\"longitude\":120.122448,\"color\":3}]";
//        JSONArray objects = JSONArray.parseArray(test);
//        return new BaseResp(ResultStatus.SUCCESS, objects);
        return new BaseResp(ResultStatus.SUCCESS, dataViewService.getMapEnterprise(this.getPageData()));
    }

    @ApiOperation(value = "查看 项目", tags = {"企业管理-监控地图"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access_token", value = "access_token"),
    })
    @RequestMapping(value = "/enterprise-mgt/map/project/get", method = RequestMethod.GET)
    public BaseResp getMapProject() {
        return new BaseResp(ResultStatus.SUCCESS, dataViewService.getMapProject(this.getPageData()));
    }

    @ApiOperation(value = "实时状态", tags = {"数据统计"})
    @RequestMapping(value = "/statistics-mgt/realstatus/get", method = RequestMethod.GET)
    public BaseResp getRealstatus() {
        return new BaseResp(ResultStatus.SUCCESS, dataViewService.getRealstatus(this.getPageData()));
    }

    @ApiOperation(value = "实时数据", tags = {"数据统计"})
    @RequestMapping(value = "/statistics-mgt/realdata/get", method = RequestMethod.GET)
    public BaseResp getRealdata(String deviceName, String boxNum, String projectNum, String roleProjectNum) {
        List<BoxData> result = new ArrayList<>();
        List<Device> devices = null;
        String[] findKeys = {"boxInterface"};
        if (!"null".equals(roleProjectNum)) {
            projectNum = roleProjectNum;
        }
        List<String> boxNums = new ArrayList<>();
        if (boxNum != null) {
            String[] split = boxNum.split(",");
            for (int i = 0; i <= split.length - 1; i++) {
                boxNums.add(split[i]);
            }
        }
        for (int i = 0; i < boxNums.size(); i++) {
            if (!StringUtils.isEmpty(projectNum)) {
                Device device = new Device();
                device.setProjectNum(projectNum);
                device.setBoxNum(boxNums.get(i));
                device.setDeviceName(deviceName);
                devices = deviceMapper.select(device);

            }
            if (ObjectUtils.isEmpty(devices)) {
                continue;
            }
            String collectionName = boxNums.get(i);
            devices.stream().forEach(device -> {
//                Map map = new HashMap();
                String findValue = device.getBoxInterface();
                String date = getTheDayBeforeYesterdayTimeFormat(-10);
                //盒子多条数据
                List<BoxData> beforeTenData = boxDataMapper.getBeforeTenData(date, findValue, collectionName);
                if (!ObjectUtils.isEmpty(beforeTenData)) {
//                    map.put("values", beforeTenData);
                    beforeTenData.stream().forEach(boxData -> {
                        result.add(boxData);

                    });
                }
            });
        }
        return new BaseResp(ResultStatus.SUCCESS, result);
    }

    @ApiOperation(value = "数据统计", tags = {"数据统计"})
    @RequestMapping(value = "/statistics-mgt/data/get", method = RequestMethod.GET)
    public BaseResp getData() {
        return new BaseResp(ResultStatus.SUCCESS, dataViewService.getData(this.getPageData()));
    }

    @ApiOperation(value = "水质监控-水质监测", tags = {"数据统计"})
    @RequestMapping(value = "/statistics-mgt/water/quality/get", method = RequestMethod.GET)
    public BaseResp getWaterQuality() {
        return new BaseResp(ResultStatus.SUCCESS, dataViewService.getWaterQuality(this.getPageData()));
    }

    @ApiOperation(value = "水质监控-水质取样", tags = {"数据统计"})
    @RequestMapping(value = "/statistics-mgt/water/sampling/get", method = RequestMethod.GET)
    public BaseResp getSampling() {
        return new BaseResp(ResultStatus.SUCCESS, dataViewService.getSampling(this.getPageData()));
    }

    @ApiOperation(value = "浓度配置", tags = {"数据统计"})
    @RequestMapping(value = "/statistics-mgt/data/concentration/get", method = RequestMethod.GET)
    public BaseResp getConcentration() {
        return new BaseResp(ResultStatus.SUCCESS, dataViewService.getConcentration(this.getPageData()));
    }

    @ApiOperation(value = "浓度配置", tags = {"数据统计"})
    @RequestMapping(value = "/statistics-mgt/data/concentration/add", method = RequestMethod.POST)
    public BaseResp addConcentration(String concentration) {
        List<Concentration> concentration1 = JSON.parseArray(concentration, Concentration.class);
        return new BaseResp(ResultStatus.SUCCESS, dataViewService.addConcentration(concentration1));
    }

    @ApiOperation(value = "浓度配置", tags = {"数据统计"})
    @RequestMapping(value = "/statistics-mgt/data/concentration/update", method = RequestMethod.POST)
    public BaseResp updateConcentration(Integer id, String inConcentration, String outConcentration) {
        return new BaseResp(ResultStatus.SUCCESS, dataViewService.updateConcentration(id, inConcentration, outConcentration));
    }

    @ApiOperation(value = "浓度配置", tags = {"数据统计"})
    @RequestMapping(value = "/statistics-mgt/data/concentration/delete", method = RequestMethod.POST)
    public BaseResp deleteConcentration(Integer id) {
        return new BaseResp(ResultStatus.SUCCESS, dataViewService.deleteConcentration(id));
    }

    @ApiOperation(value = "浓度配置-数据导出", tags = {"数据统计"})
    @RequestMapping(value = "/statistics-mgt/data/concentration/export", method = RequestMethod.GET)
    public BaseResp addConcentration(String id, HttpServletResponse response) {
        List<String> ids = new ArrayList<>();
        if (id != null) {
            //获取到的设备编号进行拆分
            String[] split = id.split(",");
            for (int i = 0; i <= split.length - 1; i++) {
                ids.add(split[i]);
            }
        } else {
            return new BaseResp(ResultStatus.config_error, "浓度编号为空");
        }
        dataViewService.excelExport(ids, response);
        return new BaseResp(ResultStatus.SUCCESS);
    }
}
